//
//  HTAddFamiliarVC.m
//  TruckUser
//
//  Created by Ting Han on 2017/10/16.
//  Copyright © 2017年 Ting Han. All rights reserved.
//

#import "HTAddFamiliarVC.h"
#import "HTAddFamiliarCell.h"
#import "UIView+Layout.h"
#import "HTSearchTruckDriverVC.h"

//弹框
//出发地，目的地
#import "HTAreaChoiceView.h"
//车长车型
#import "HTScanTruckType.h"
#import "HTRefreshMoreModel.h"
#import "HTMLocationManager.h"
#import "HTDriverMainVC.h"



@interface HTAddFamiliarVC ()<UITableViewDelegate,UITableViewDataSource,HTAreaChoiceViewDelegate,HTScanTruckTypeDelegate>
@property (weak, nonatomic) IBOutlet UIView *truckTypeView;
@property (weak, nonatomic) IBOutlet UIImageView *truckTypeImageView;
@property (weak, nonatomic) IBOutlet UILabel *truckTypeLabel;
@property (weak, nonatomic) IBOutlet UIView *startView;
@property (weak, nonatomic) IBOutlet UIImageView *startImageView;
@property (weak, nonatomic) IBOutlet UILabel *startLabel;

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *safeBottomHeight;


//弹框
@property (nonatomic,strong) HTAreaChoiceView *areaChoiceView;
@property (nonatomic,strong) HTScanTruckType *truckLengthTypeView;

#pragma mark --- 数据处理
//弹框数据
@property (nonatomic,strong) NSMutableArray *selectedLengthData;
@property (nonatomic,strong) HTTruckTypeModel *selectedTruckType;
@property (nonatomic,assign) BOOL isLessThanTruck;

@property (nonatomic,strong) NSMutableArray *dataSource;

@property (nonatomic,strong) NSString *currentCity;
@property (nonatomic,strong) NSString *startAddress;
@property (nonatomic,strong) NSString *isEmptyString;
@property (nonatomic,strong) NSString *lengthString;
@property (nonatomic,strong) NSString *truckTypeString;

@property (nonatomic,assign) NSInteger pageNumber;
@property (nonatomic,strong) HTRefreshMoreModel *refreshMoreModel;

@end

@implementation HTAddFamiliarVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.safeBottomHeight.constant = IPHONE_SAFEBOTTOMAREA_HEIGHT + kHTToolBarHeight + IPHONE_NAVIGATIONBAR_HEIGHT;
    self.startAddress = @"全国";
    self.isEmptyString = @"0";
    self.lengthString = @"0";
    self.truckTypeString = @"";
    self.startLabel.text = @"全国";
    [self configTableView];
    [self tapGesture];
    self.pageNumber = 1;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.tableView.mj_header beginRefreshing];
}
#pragma mark --- 界面绘制
- (void)tapGesture{
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didTapGesture:)];
    [self.startView addGestureRecognizer:tap1];
    UITapGestureRecognizer *tap3 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didTapGesture:)];
    [self.truckTypeView addGestureRecognizer:tap3];
}

- (void)configTableView{
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.width = kHTScreenWidth;
    self.tableView.backgroundColor = kBackgroundColor;
    [self.tableView registerNib:[UINib nibWithNibName:@"HTAddFamiliarCell" bundle:nil] forCellReuseIdentifier:AddFamiliarCell];
    self.tableView.estimatedRowHeight =0;
    self.tableView.estimatedSectionHeaderHeight =0;
    self.tableView.estimatedSectionFooterHeight =0;
    [self configTableHeader];
    self.tableView.mj_header = self.header;
    
}


- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
    
}

#pragma mark --- tableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 105;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HTAddFamiliarCell *cell = [tableView dequeueReusableCellWithIdentifier:AddFamiliarCell forIndexPath:indexPath];
    cell.addFamiliarModel = self.dataSource[indexPath.row];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return kWidth(60);
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kHTScreenWidth, kWidth(60))];
    view.backgroundColor = [UIColor whiteColor];
    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(kWidth(15), kWidth(8), view.width - kWidth(30), view.height - kWidth(16))];
    backView.backgroundColor = kBackgroundColor;
    backView.layer.masksToBounds = YES;
    backView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    backView.layer.borderWidth = 0.3;
    [view addSubview:backView];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, backView.width, backView.height)];
    label.text = @"    通过车牌号、车号搜索司机";
    label.font = [UIFont systemFontOfSize:13];
    label.textColor = [UIColor darkGrayColor];
    [backView addSubview:label];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(didPushSearch)];
    [view addGestureRecognizer:tap];
    return view;
}
- (void)didPushSearch{
    HTSearchTruckDriverVC *search = [[HTSearchTruckDriverVC alloc]init];
    [self.navigationController pushViewController:search animated:YES];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    HTDriverMainVC *driver = [[HTDriverMainVC alloc]init];
    HTAddFamiliarModel *model = self.dataSource[indexPath.row];
    driver.ID = model.driverinfor;
    [self.navigationController pushViewController:driver animated:YES];
}

#pragma mark --- 选中起始地，目的地，车长车型部分
- (void)didTapGesture:(UITapGestureRecognizer *)sender{
    
    switch ([sender view].tag) {
        case 111://出发地
        {
            [self removeTruckLengthTypeView];
            if (self.areaChoiceView && self.areaChoiceView.areaChoiceType == HTAreaChoiceTypeStart) {//点击了同一个,收起
                [self removeAreaChoiceView];
                //设置tab选中状态
                [self setTabViewWithIndex:3];
                return;
            }
            if (self.areaChoiceView && self.areaChoiceView.areaChoiceType == HTAreaChoiceTypeDestination) {//同一个View，但是类型不同，刷新数据
                self.areaChoiceView.areaChoiceType = HTAreaChoiceTypeStart;
                [self.areaChoiceView reloadAllData];
                [self setTabViewWithIndex:0];
                return;
            }
            [self setupAreaViewWithType:HTAreaChoiceTypeStart];
            [self setTabViewWithIndex:0];
        }
            break;
        case 114://车型车长
        {
            [self removeAreaChoiceView];
            if (!self.truckLengthTypeView) {
                [self setupTruckLengthTypeView];
                [self setTabViewWithIndex:2];
            }else{
                [self removeTruckLengthTypeView];
                [self setTabViewWithIndex:3];
            }
        }
            break;
        default:
            break;
    }
}
//选中起始地，目的地，车长车型部分
- (void)setTabViewWithIndex:(NSInteger)index{
    switch (index) {
        case 0://起始地
        {
            [self setTabViewSelected:YES withImageView:self.startImageView withLabel:self.startLabel];
            [self setTabViewSelected:NO withImageView:self.truckTypeImageView withLabel:self.truckTypeLabel];
        }
            break;
        case 2://车长车型
        {
            [self setTabViewSelected:NO withImageView:self.startImageView withLabel:self.startLabel];
            [self setTabViewSelected:YES withImageView:self.truckTypeImageView withLabel:self.truckTypeLabel];
        }
            break;
        case 3://均不选中
        {
            [self setTabViewSelected:NO withImageView:self.startImageView withLabel:self.startLabel];
            [self setTabViewSelected:NO withImageView:self.truckTypeImageView withLabel:self.truckTypeLabel];
        }
            break;
        default:
            break;
    }
}
- (void)setTabViewSelected:(BOOL)selected withImageView:(UIImageView *)imageView withLabel:(UILabel *)label{
    if (selected) {
        imageView.image = [[UIImage imageNamed:@"arrow_solid_up"]imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        imageView.tintColor = kBlueColor;
        label.textColor = kBlueColor;
    }else{
        imageView.image = [[UIImage imageNamed:@"arrow_solid_down"]imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        imageView.tintColor = [UIColor blackColor];
        label.textColor = [UIColor blackColor];
    }
}
#pragma mark -------- 处理弹框选择出发地目的地的操作
//出发地目的地弹框View
- (void)setupAreaViewWithType:(HTAreaChoiceType)type{
    if (!self.areaChoiceView) {
        self.areaChoiceView = [[HTAreaChoiceView alloc]initWithFrame:CGRectMake(0, self.startView.bottom, kHTScreenWidth, kHTScreenHeight - self.startView.bottom - kHTNavicationBarAndStatusBar)];
        self.areaChoiceView.areaChoiceType = type;
        self.areaChoiceView.delegate = self;
        __weak __typeof(self)weakSelf = self;
        self.areaChoiceView.blockCallBack = ^{
            [weakSelf removeAreaChoiceView];
            [weakSelf setTabViewWithIndex:3];
        };
        [self.view addSubview:self.areaChoiceView];
    }
}
//移除弹框，出发地目的地
- (void)removeAreaChoiceView{
    if (self.areaChoiceView) {
        [self.areaChoiceView removeFromSuperview];
        self.areaChoiceView = nil;
    }
}
//代理
- (void)didChoiceItemWithAreaModel:(HTAreaModel *)areaModel currentIndex:(NSInteger)currentIndex areaChoiceType:(HTAreaChoiceType)areaChoiceType{
   
    if (areaModel.areaType == HTAreaTypeNo || areaModel.areaType == HTAreaTypeArea) {
        [self removeAreaChoiceView];
        [self setTabViewWithIndex:3];
        NSString *place = [HTUtils placePostStringWith:areaModel];
        if (areaChoiceType == HTAreaChoiceTypeStart) {//出发地
            self.startLabel.text = areaModel.title;
            self.startAddress = place;
            //调用刷新网络请求
            [self.tableView.mj_header beginRefreshing];
        }
    }
}
- (void)didChoiceItemWithHistory:(HTAreaModel *)areaModel areaChoiceType:(HTAreaChoiceType)areaChoiceType{
    
    //调用刷新网络请求
    [self removeAreaChoiceView];
    [self setTabViewWithIndex:3];
    if (areaChoiceType == HTAreaChoiceTypeStart) {//出发地
        NSString *place = [HTUtils placePostStringWith:areaModel];
        self.startLabel.text = areaModel.title;
        self.startAddress = place;
        //调用刷新网络请求
        [self.tableView.mj_header beginRefreshing];
    }
}

#pragma mark --- 处理弹框车长车型
- (void)setupTruckLengthTypeView{
    if (!self.truckLengthTypeView) {
        self.truckLengthTypeView = [[HTScanTruckType alloc]initWithFrame:CGRectMake(0, self.startView.bottom, kHTScreenWidth, kHTScreenHeight - self.startView.bottom - kHTNavicationBarAndStatusBar)];
        self.truckLengthTypeView.delegate = self;
        __weak __typeof(self)weakSelf = self;
        self.truckLengthTypeView.blockCallBack = ^{
            [weakSelf removeTruckLengthTypeView];
            [weakSelf setTabViewWithIndex:3];
        };
        [self.view addSubview:self.truckLengthTypeView];
    }
}
//移除弹框，车长车型
- (void)removeTruckLengthTypeView{
    if (self.truckLengthTypeView) {
        [self.truckLengthTypeView removeFromSuperview];
        self.truckLengthTypeView = nil;
    }
}
- (void)didClickConformWithLengths:(NSMutableArray *)lengthsData TruckType:(HTTruckTypeModel *)truckType isLessThanTruck:(BOOL)isLessThanTruck{
    self.selectedLengthData = lengthsData;
    self.selectedTruckType = truckType;
    self.isLessThanTruck = isLessThanTruck;
    NSString *total = @"";
    total = [NSString stringWithFormat:@"%@,%@",total,[HTUtils sortLengthDataDisplayStringWithArray:lengthsData]];
    NSInteger index = 1;
    if ([total isEqualToString:@",不限车长"]) {
        total = @"";
        index = 0;
    }
    if (!(truckType.truckTypeModelType == TruckTypeModelTypeUnlimited)) {
        if (index < 2) {
            total = [NSString stringWithFormat:@"%@,%@",total,truckType.title];
            index++;
        }
    }
    if (total.length <= 0) {
        total = @"车长车型";
    }else{
        total = [total substringFromIndex:1];
    }
    if (self.isLessThanTruck) {
        self.isEmptyString = @"1";
    }else{
        self.isEmptyString = @"0";
    }
    self.truckTypeLabel.text = total;
    [self removeTruckLengthTypeView];
    [self setTabViewWithIndex:3];
    //调用刷新网络请求
    [self.tableView.mj_header beginRefreshing];
}
#pragma mark --- 网络请求
- (void)loadNewData{
    [self netLoadFamiliar];
}
- (void)netLoadFamiliar{
    [HTHttpRequestManager requestTruckListWithCarstate:self.startAddress length:self.lengthString cargotype:self.truckTypeString state:self.isEmptyString Success:^(id  _Nullable responseObject) {
        [self.tableView.mj_header endRefreshing];
        DBLog(@"熟车列表：%@",responseObject);
        if (!responseObject) {
            [HTShowUtil showMessage:@"熟车列表请求失败"];
            return;
        }
        NSString *codeStr = [NSString stringWithFormat:@"%@",responseObject[@"code"]];
        if (![codeStr isEqualToString:@"200"]) {
            [HTShowUtil showMessage:responseObject[@"message"]];
            return;
        }
        self.dataSource = [HTAddFamiliarModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"data"]];
        [self.tableView reloadData];
    } failure:^(NSError * _Nonnull error) {
          [self.tableView.mj_header endRefreshing];
    }];
}


@end
